package com.hepinghospital.user.ui.activity.userinfo;

import android.app.ProgressDialog;
import android.content.Intent;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;

import com.gyf.immersionbar.ImmersionBar;
import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.service.WebSocketService;
import com.hepinghospital.user.ui.MainActivity;
import com.hepinghospital.user.ui.WebViewActivity;
import com.hepinghospital.user.ui.widget.ClearEditText;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.client.RestClient;
import com.rest.observer.BaseObserver;
import com.rest.response.LoginResponse;

import butterknife.BindView;
import butterknife.OnClick;
import jz.joyoung.robot.util.AES128;
import jz.joyoung.robot.util.PreferencesHelper;
import jz.joyoung.robot.util.SoftKeyboardUtil;
import jz.joyoung.robot.util.UtilString;


/**
 * @author Administrator
 * @date 2018/5/25
 */

public class LoginActivity extends BaseActivity {
    @BindView(R.id.username)
    EditText username;
    @BindView(R.id.password)
    ClearEditText password;
    @BindView(R.id.chk_save)
    CheckBox chkSave;
    @BindView(R.id.chk_agree)
    CheckBox chkAgree;
    @BindView(R.id.iv_password_hide)
    ImageView ivPasswordHide;

    private boolean isShowPassword = false;
    private ProgressDialog mDialog;


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_login;
    }

    @Override
    protected void initViews() {
    }

    @Override
    protected void initData() {
        if (PreferencesHelper.getInstance().getBoolean(this, "isSave")) {
            chkSave.setChecked(true);
            username.setText(PreferencesHelper.getInstance().getString(this, "username"));
            password.setText(PreferencesHelper.getInstance().getString(this, "password"));
        } else {
            chkSave.setChecked(false);
        }

        if (PreferencesHelper.getInstance().getBoolean(this, "isAgree")) {
            chkAgree.setChecked(true);
        } else {
            chkAgree.setChecked(false);
        }
    }

    @Override
    protected void doBeforeSetcontentView() {
        ImmersionBar.with(this).keyboardEnable(false).transparentStatusBar().fitsSystemWindows(false).statusBarDarkFont(true).navigationBarColor(R.color.black).autoDarkModeEnable(true).init();
    }


    @OnClick({R.id.btn_forget_password, R.id.btn_login, R.id.btn_register, R.id.tv_agree, R.id.iv_password_hide})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_forget_password:
                startActivity(ForgetActivity.class);
                break;
            case R.id.btn_login:
                SoftKeyboardUtil.hideSoftKeyboard(mContext);
                RestClient.getInstance().clearSession();
                login();
                break;
            case R.id.btn_register:
                startActivity(RegisterActivity.class);
                break;
            case R.id.tv_agree:
                startActivity(new Intent(mContext, WebViewActivity.class).putExtra("fromWhere", "LoginActivity").putExtra("rulesType", "7"));
                break;
            case R.id.iv_password_hide:
                if (isShowPassword) {
                    ivPasswordHide.setImageResource(R.mipmap.icon_password_open);
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                    ivPasswordHide.setImageResource(R.mipmap.icon_password_hide);
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                isShowPassword = !isShowPassword;
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
    }

    private void login() {
        String mPassword = password.getText().toString().trim();
        String mPhone = username.getText().toString().trim();
        if (UtilString.isEmpty(mPhone) || !UtilString.isPhoneNumNo(mPhone)) {
            ToastUtil.showToastCenter(mContext, "请输入正确的手机号");
            return;
        }

        if (UtilString.isEmpty(mPassword)) {
            ToastUtil.showToastCenter(mContext, "密码不能为空");
            return;
        }
        if (!chkAgree.isChecked()) {
            ToastUtil.showToastCenter(mContext, "请先阅读并同意法律声明及隐私权政策");
            return;
        }

        showLoginDialog(getString(R.string.logining_msg));
        try {
            RestProxy.getInstance().login(AES128.encryptStringAES(mPhone, "7t3e506jaa10xbd4"), AES128.encryptStringAES(mPassword, "7t3e506jaa10xbd4"), "", new BaseObserver<LoginResponse>() {

                @Override
                public void onError(Throwable e) {
                    super.onError(e);
                    dismissLoginDialog();
                    ToastUtil.onError(LoginActivity.this, e);
                }

                @Override
                public void onSuccess(LoginResponse loginResponse) {
                    dismissLoginDialog();
                    BaseApplication.currentUserId = loginResponse.userId;
                    BaseApplication.name = loginResponse.name;
                    BaseApplication.avatar = loginResponse.avatar;
                    BaseApplication.sex = loginResponse.sex;
                    BaseApplication.mobile = loginResponse.mobile;
                    BaseApplication.xyAccount = loginResponse.videoAccountDTO.account;
                    BaseApplication.xyPassword = loginResponse.videoAccountDTO.password;
                    PreferencesHelper.getInstance().set(mContext, "accessToken", loginResponse.token);
                    PreferencesHelper.getInstance().set(mContext, "userId", loginResponse.userId);
                    PreferencesHelper.getInstance().set(mContext, "username", username.getText().toString());
                    PreferencesHelper.getInstance().set(mContext, "password", password.getText().toString());
                    PreferencesHelper.getInstance().set(mContext, "mobile", loginResponse.mobile);
                    PreferencesHelper.getInstance().set(mContext, "xyAccount", loginResponse.videoAccountDTO.account);
                    PreferencesHelper.getInstance().set(mContext, "xyPassword", loginResponse.videoAccountDTO.password);
                    BaseApplication.userType = loginResponse.hosType;
                    RestClient.getInstance().token = loginResponse.token;
                    PreferencesHelper.getInstance().set(LoginActivity.this, "isSave", chkSave.isChecked());
                    PreferencesHelper.getInstance().set(LoginActivity.this, "isAgree", chkAgree.isChecked());
                    checkServiceRunning(mContext);
                    startActivity(MainActivity.class);
                    finish();
                }
            });
        } catch (
                Exception e) {
            e.printStackTrace();
        }
    }


    public void showLoginDialog(String msg) {
        if (null == mDialog) {
            mDialog = new ProgressDialog(this);
        }

        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setTitle(msg);
        mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mDialog.show();
    }

    public void dismissLoginDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        stopService(new Intent(mContext, WebSocketService.class));
    }
}
